//
//  HomeViewModel.swift
//  ShouChong
//
//  Created by yw on 2024/8/12.
//

import Foundation

struct HomeModel:Identifiable,Codable {
    var id:Int = 0
    var createTime:String = ""
    var count:String = ""
    var uid:String = ""
    var remark:String = ""
    var other:String = ""
    var duration:String = ""
    var heartRate:String = ""
    var isWatch:String = ""
}


class HomeViewModel:ObservableObject {
    @Published var model:HomeModel = HomeModel()
    
    init() {
        getUserDataWithDate(date: Date(),completion: nil)
    }
    
    func getUserDataWithDate(date:Date,completion:(() -> Void)?) {
        var components = Calendar.current.dateComponents([.year, .month, .day], from: date)
        guard let startDate = Calendar.current.date(from: components) else {
            return
        }
        components.day = components.day?.advanced(by: 1)
        guard let endOfDay = Calendar.current.date(from: components),
              let endDate = Calendar.current.date(byAdding: .second, value: -1, to: endOfDay) else {
            return
        }
        
        let sendData = [
            "startDate":String().date2String(startDate),
            "endDate":String().date2String(endDate),
        ]
        YWNetworkTool.share().requestJson(url: "info/getNNHistoryWithDate", parameters: sendData) { res in
            DPrint(res)
            guard let results = res as? [String:Any],
                  let data = results["data"] as? [String:Any],
                  let jsonData = try? JSONSerialization.data(withJSONObject: data) else {
//                self.model = HomeModel()
                YWToast.show(text: "获取当日数据失败")
                return
            }
            do {
                let model = try JSONDecoder().decode(HomeModel.self, from: jsonData)
//                DPrint(model)
                self.model = model
                completion?()
            } catch {
//                self.model = HomeModel()
                YWToast.show(text: "获取数据失败")
                DPrint(error.localizedDescription)
            }
        } responseFailBlock: { error, code in
//            self.model = HomeModel()
            YWToast.show(text: "获取数据失败")
        }

    }
    
    
    
    
}
